<script setup>
/**
 * 聊天窗口组件 - 负责消息展示和用户输入处理
 */

import { ref, watch, nextTick } from 'vue'
import { ElCard, ElInput, ElButton, ElLoading, ElMessage } from 'element-plus'

// 组件属性定义
const props = defineProps({
  messages: {
    type: Array,
    required: true
  },
  isLoading: {
    type: Boolean,
    default: false
  }
})

// 定义事件发射器
const emit = defineEmits(['send'])

// 响应式状态
const message = ref('') // 当前输入的消息内容
const messagesContainer = ref(null) // 消息容器引用

// 监听消息变化，自动滚动到底部
watch(() => props.messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTo({
      top: messagesContainer.value.scrollHeight,
      behavior: 'smooth'
    })
  }
}

/**
 * 处理消息发送
 */
const handleSend = () => {
  if (message.value.trim()) {
    emit('send', message.value) // 触发send事件
    message.value = '' // 清空输入框
  }
}

/**
 * 复制消息内容到剪贴板
 * @param {string} text - 要复制的消息内容
 */
const copyMessage = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      ElMessage.success('Copied to clipboard') // 显示成功提示
    })
    .catch(() => {
      ElMessage.error('Failed to copy text') // 显示失败提示
    })
}
</script>

<template>
  <!-- 主容器 -->
  <div class="flex flex-col h-[calc(100vh-120px)] md:h-[calc(100vh-200px)] p-2 md:p-4 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700">
    <!-- 消息展示区域 -->
    <div 
      ref="messagesContainer"
      class="flex-1 overflow-y-hidden space-y-4 mb-4 scroll-smooth p-4"
      style="scrollbar-width: none; -ms-overflow-style: none;"
    >
      <!-- 消息列表 -->
      <div
        v-for="(msg, index) in messages"
        :key="index"
        class="flex items-start gap-3"
        :class="{
          'flex-row-reverse': msg.role === 'user',
          'flex-row': msg.role === 'assistant'
        }"
      >
        <!-- 用户头像 -->
        <div class="w-10 h-10 rounded-full overflow-hidden">
          <img
            v-if="msg.role === 'user'"
            src="https://i.pravatar.cc/150?img=3"
            alt="User Avatar"
            class="w-full h-full object-cover"
          />
          <img
            v-else
            src="https://i.pravatar.cc/150?img=5"
            alt="AI Avatar"
            class="w-full h-full object-cover"
          />
        </div>

        <!-- 消息气泡 -->
        <el-card
          class="w-full rounded-lg transition-all duration-300"
          :style="{
            maxWidth: msg.content.length > 100 ? '80%' : '60%',
            minWidth: '200px',
            width: 'fit-content'
          }"
          :class="{
            'bg-gray-50 dark:bg-gray-700': msg.role === 'user',
            'bg-gray-100 dark:bg-gray-800': msg.role === 'assistant',
            'ml-auto': msg.role === 'user'
          }"
          :shadow="msg.role === 'user' ? 'hover' : 'never'"
        >
          <!-- 消息内容 -->
          <div class="text-gray-900 dark:text-gray-100">{{ msg.content }}</div>
          <!-- 消息时间戳 -->
          <div class="mt-2 text-xs text-gray-500 dark:text-gray-300">
            {{ new Date(msg.timestamp).toLocaleString() }}
          </div>
        </el-card>
      </div>

      <!-- 加载指示器 -->
      <div v-if="isLoading" class="flex justify-center py-4">
        <div class="flex items-center gap-3">
          <div class="animate-spin">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-2">
              <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
            </svg>
          </div>
          <span class="text-gray-500 dark:text-gray-300">AI is thinking...</span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="sticky bottom-0 pt-4 pb-4">
      <div class="container mx-auto px-4">
        <div class="relative">
          <div class="flex items-end gap-2 w-full">
            <el-input
              v-model="message"
              placeholder="Type your message..."
              @keyup.enter="handleSend"
              type="textarea"
              :rows="3"
              resize="none"
              class="flex-1 rounded-xl bg-white dark:bg-gray-700 shadow-sm hover:shadow-md transition-shadow duration-300 focus-within:ring-2 focus-within:ring-primary/50"
            />
            <el-button
              type="primary"
              @click="handleSend"
              :disabled="isLoading"
              class="h-[calc(3rem+12px)] px-6 bg-primary hover:bg-primary/90 text-white transition-all duration-300 rounded-lg"
            >
              Send
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/**
 * 卡片动画效果
 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/**
 * 自定义加载动画
 */
.custom-loading :deep(.el-loading-spinner) {
  animation: spin 1s linear infinite;
}

.custom-loading :deep(.el-loading-spinner .path) {
  stroke: #3b82f6;
  stroke-width: 4;
  stroke-linecap: round;
  animation: dash 1.5s ease-in-out infinite;
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes dash {
  0% {
    stroke-dasharray: 1, 150;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -35;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -124;
  }
}
</style>
